package com.jn.musicdemo.service;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.Nullable;

import com.jn.musicdemo.event.MusicEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;

public class CustomService extends Service {

    private MediaPlayer mMediaPlayer;
    private OnMusicPlayStateChangeListener mOnMusicPlayStateChangeListener;
    private Cursor mCursor;
    private ContentResolver mContentResolver;

    @Override
    public void onCreate() {
        super.onCreate();
        initPlayer();
        mContentResolver = getContentResolver();
        initPlaylist();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String data = intent.getStringExtra("data");
        Uri dataUri = Uri.parse(data);
        if (mMediaPlayer != null) {
            try {
                mMediaPlayer.reset();
                mMediaPlayer.setDataSource(getApplicationContext(), dataUri);
                mMediaPlayer.prepare();
                mMediaPlayer.start();
                EventBus.getDefault().post(new MusicEvent("play"));
                // 调用新方法更新UI显示当前播放的歌曲信息
                getCurrentPlayingSongInfo();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        mMediaPlayer.stop();
        mMediaPlayer.release();
        mMediaPlayer = null;
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("asdf", "=======onUnbind=======");
        return super.onUnbind(intent);
    }

    @Override
    public void onRebind(Intent intent) {
        Log.d("asdf", "=======onRebind=======");
        super.onRebind(intent);
    }

    public final class MyBinder extends Binder {
        public CustomService getService() {
            return CustomService.this;
        }
    }

    private void initPlayer() {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                Log.d("asdf", "播放结束!");
                playNextSong();
            }
        });
        mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                return true;
            }
        });
    }

    private void initPlaylist() {
        Uri contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String[] projection = new String[]{
                MediaStore.Audio.Media._ID,
                MediaStore.Audio.Media.TITLE,
                MediaStore.Audio.Media.ARTIST,
                MediaStore.Audio.Media.DATA};
        String selection = MediaStore.Audio.Media.DATA + " LIKE ? ";
        String[] selectionArgs = {"%/DownLoad/WeiXin/%"};
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";

        if (mContentResolver != null) {
            mCursor = mContentResolver.query(
                    contentUri, projection, selection, selectionArgs, sortOrder);
            if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onMusicListChanged(mCursor);
            }
        }
    }

    public Cursor getCursor() {
        return mCursor;
    }

    private void playNextSong() {
        if (mCursor != null) {
            if (mCursor.moveToNext()) {
            } else if (mCursor.moveToFirst()) {
            }
            getDataByCursor(mCursor);
        }
    }

    public void getDataByCursor(int position) {
        if (mCursor != null && mCursor.moveToPosition(position)) {
            getDataByCursor(mCursor);
        }
    }

    private void getDataByCursor(Cursor cursor) {
        int titleIndex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistIndex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
        int dataIndex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
        if (titleIndex >= 0 && artistIndex >= 0) {
            String title = cursor.getString(titleIndex);
            String artist = cursor.getString(artistIndex);
            String data = cursor.getString(dataIndex);
            Uri dataUri = Uri.parse(data);
            if (mMediaPlayer != null) {
                try {
                    mMediaPlayer.reset();
                    mMediaPlayer.setDataSource(getApplicationContext(), dataUri);
                    mMediaPlayer.prepare();
                    mMediaPlayer.start();
                    EventBus.getDefault().post(new MusicEvent("play"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (mOnMusicPlayStateChangeListener != null) {
                mOnMusicPlayStateChangeListener.onMusicInfoChanged(title, artist);
            }
        }
    }

    public void play() {
        if (mMediaPlayer != null) {
            mMediaPlayer.start();
            EventBus.getDefault().post(new MusicEvent("play"));
        }
    }

    public void pause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            EventBus.getDefault().post(new MusicEvent("stop"));
        }
    }

    public void last() {
        Log.d("asdf", "=======last=======");
        if (mCursor != null) {
            if (mCursor.moveToPrevious()) {
            } else if (mCursor.moveToLast()) {
            }
            getDataByCursor(mCursor);
        }
    }

    public void next() {
        Log.d("asdf", "=======next=======");
        if (mCursor != null) {
            if (mCursor.moveToNext()) {
            } else if (mCursor.moveToFirst()) {
            }
            getDataByCursor(mCursor);
        }
    }

    public int getDuration() {
        int duration = 0;
        if (mMediaPlayer != null) {
            duration = mMediaPlayer.getDuration();
        }
        return duration;
    }

    public int getCurrentPosition() {
        int position = 0;
        if (mMediaPlayer != null) {
            position = mMediaPlayer.getCurrentPosition();
        }
        return position;
    }

    public boolean isPlaying() {
        if (mMediaPlayer != null) {
            return mMediaPlayer.isPlaying();
        }
        return false;
    }

    public void seekTo(int progress) {
        if (mMediaPlayer != null) {
            Log.d("asdf", "seekTo ==" + progress);
            mMediaPlayer.seekTo(progress);
        }
    }

    public void setOnMusicPlayStateChangeListener(OnMusicPlayStateChangeListener l) {
        mOnMusicPlayStateChangeListener = l;
    }

    public interface OnMusicPlayStateChangeListener {
        void onPlayStart();
        void onPlayStop();
        void onPlayComplete();
        void onMusicInfoChanged(String title, String artist);
        void onMusicListChanged(Cursor cursor);
    }

    /**
     * 获取当前正在播放的歌曲的信息（歌名和歌手名）。
     */
    public String[] getCurrentPlayingSongInfo() {
        if (mCursor == null || !mMediaPlayer.isPlaying()) {
            return new String[]{"未知", "未知"};
        }

        mCursor.moveToPosition(mMediaPlayer.getCurrentPosition());
        int titleIndex = mCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
        int artistIndex = mCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);

        String title = mCursor.getString(titleIndex);
        String artist = mCursor.getString(artistIndex);
        return new String[]{title, artist};
    }
}